//
//  UUFleetVC.m
//  UUCharterSupplier
//
//  Created by ZhangAo on 21/01/2018.
//  Copyright © 2018 UUCharter. All rights reserved.
//

#import "UUFleetVC.h"
#import "UUBaseTableViewCell.h"
#import "UUResourceManager.h"
#import "UUFleetManager.h"
#import <UUFoundation/UUCityManager.h>
#import "UUFleetEditVC.h"
#import "UUPermissionManager.h"

@interface UUFleetCell : UUBaseTableViewCell

@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UILabel *leaderLabel;
@property (nonatomic, strong) UILabel *cityLabel;

@end

@implementation UUFleetCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.nameLabel = [UILabel new];
        self.nameLabel.font = [UIFont systemFontOfSize:16];
        [self.contentView addSubview:self.nameLabel];
        
        self.leaderLabel = [UILabel new];
        self.leaderLabel.font = [UIFont systemFontOfSize:15];
        [self.contentView addSubview:self.leaderLabel];
        
        self.cityLabel = [UILabel new];
        self.cityLabel.font = [UIFont systemFontOfSize:14];
        self.cityLabel.textColor = COMMON_TEXT_LIGHT_COLOR;
        [self.contentView addSubview:self.cityLabel];
        
        [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(15);
            make.top.mas_equalTo(15);
        }];
        
        [self.leaderLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.nameLabel.mas_left);
            make.top.equalTo(self.nameLabel.mas_bottom).offset(15);
        }];
        
        [self.cityLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.nameLabel.mas_top);
            make.trailing.mas_equalTo(-15);
            make.trailing.equalTo(self.leaderLabel.mas_trailing);
        }];
    }
    
    return self;
}

@end

/////////////////////////////////////////////

@interface UUFleetVC () <UUFleetManagerObserver>

@property (nonatomic, copy) NSArray<NSNumber *> *fleets;

@end

@implementation UUFleetVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.backgroundColor = COMMON_BACKGROUND_COLOR;
    self.tableView.rowHeight = 90;
    
    if ([self canAddFleet]) {
        self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithTitle:GetResourceManager().addIconText
                                                                                  target:self
                                                                                selector:@selector(addFleet:)];
    }
    
    [self.tableView registerClass:[UUFleetCell class] forCellReuseIdentifier:@"Cell"];
    
    [self reloadFleet];
    
    [GetFleetManager() addObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)canAddFleet {
    return YES && [GetPermissionManager() checkPermission:UUPermissionFlagFleetReadWrite];
}

- (IBAction)addFleet:(id)sender {
    UUFleetEditVC *editVC = [UUFleetEditVC instanceOfAppropriate];
    editVC.editable = YES;
    [self.navigationController pushViewController:editVC animated:YES];
}

- (void)reloadFleet {
    self.fleets = [GetFleetManager() fetchFleets];
    [self.tableView reloadData];
}

- (void)configCell:(UITableViewCell *)cell forIndexPath:(NSIndexPath *)indexPath {
    
}

- (NSNumber *)fleetIdForIndexPath:(NSIndexPath *)indexPath {
    return self.fleets[indexPath.row];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.fleets.count;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UUFleetCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    
    NSNumber *fleetId = self.fleets[indexPath.row];
    UUFleetModel *fleet = [GetFleetManager() fetchFleetWithFleetId:fleetId];
    
    cell.nameLabel.text = fleet.name;
    cell.leaderLabel.text = fleet.contact;
    
    NSArray<NSString *> *districtIds = [fleet.districtIds componentsSeparatedByString:@","];
    NSMutableArray<NSString *> *cityNames = [NSMutableArray new];
    for (int i = 0; i < MIN(2, districtIds.count); ++i) {
        NSString *district = districtIds[i];
    
        UUCityModel *city = [GetCityManager() fetchCityWithCityId:@([district integerValue])];
        [cityNames addObject:city.simpleName ?: @""];
    }
    
    if (districtIds.count > 2) {
        cell.cityLabel.text = [NSString stringWithFormat:@"%@等%ld个城市", [cityNames componentsJoinedByString:@","], districtIds.count];
    } else {
        cell.cityLabel.text = [cityNames componentsJoinedByString:@","];
    }
    
    [self configCell:cell forIndexPath:indexPath];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSNumber *fleetId = self.fleets[indexPath.row];

    UUFleetEditVC *editVC = [UUFleetEditVC instanceOfAppropriate];
    editVC.editable = NO;
    editVC.fleetId = fleetId;
    
    [self.navigationController pushViewController:editVC animated:YES];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    return [self canAddFleet];
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [UIAlertController presentAlertControllerWithTitle:@"确定删除该车队吗？" message:nil doneBlock:^{
            NSNumber *fleetId = self.fleets[indexPath.row];
            
            ShowIndicator();
            WEAK_SELF();
            [GetFleetManager() asyncDeleteFleetWithFleetId:fleetId completeBlock:^(NSError *error) {
                HideIndicatorInView(weakSelf.view);
                
                if (error != nil) {
                    ShowTipsOnView(error.localizedDescription, weakSelf.view);
                }
            }];
        } cancelBlock:nil];
    }
}

#pragma mark - UUFleetManagerObserver methods

- (void)fleetManagerDidUpdateFleets {
    [self reloadFleet];
}

- (void)fleetManagerDidDeleteFleets:(NSArray<NSNumber *> *)fleets {
    if (self.fleets.count > 0) {
        NSMutableArray<NSIndexPath *> *indexPathes = [NSMutableArray array];
        NSMutableIndexSet *indexSet = [NSMutableIndexSet new];
        for (int j = 0; j < fleets.count; ++j) {
            for (int i = 0; i < self.fleets.count; ++i) {
                if ([self.fleets[i] isEqual:fleets[j]]) {
                    [indexPathes addObject:[NSIndexPath indexPathForRow:i inSection:0]];
                    [indexSet addIndex:i];
                    break;
                }
            }
        }
        
        NSMutableArray<NSNumber *> *mutableFleets = [self.fleets mutableCopy];
        [mutableFleets removeObjectsAtIndexes:indexSet];
        self.fleets = mutableFleets;
        [self.tableView deleteRowsAtIndexPaths:indexPathes
                              withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}

@end
